import { createRouter, createWebHistory } from 'vue-router'
// 直接导入OrderSuccess组件以确保正确加载
//import OrderSuccess from '../views/OrderSuccess.vue'
//console.log('OrderSuccess组件导入结果:', OrderSuccess);

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/Home.vue'),
    meta: { title: '智能酒桶商城' }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue'),
    meta: { title: '注册' }
  },
  {
    path: '/forget-password',
    name: 'ForgetPassword',
    component: () => import('../views/ForgetPassword.vue'),
    meta: { title: '忘记密码' }
  },
  {
    path: '/device-info/:deviceId',
    name: 'DeviceInfo',
    component: () => import('../views/DeviceInfo.vue'),
    meta: { title: '设备信息', requiresAuth: false }
  },
  {
    path: '/order-confirm',
    name: 'OrderConfirm',
    component: () => import('../views/OrderConfirm.vue'),
    meta: { title: '确认订单', requiresAuth: true }
  },
  {
    path: '/order-success/:orderId',
    name: 'OrderSuccess',
    component: () => import('../views/OrderSuccess.vue'),
    meta: { title: '订单成功', requiresAuth: false },
    // beforeEnter: (to, from, next) => {
    //   console.log('OrderSuccess 路由匹配成功，准备加载组件');
    //   console.log('路由参数:', to.params);
    //   next();
    // }
  },
  {
    path: '/user',
    name: 'User',
    component: () => import('../views/User.vue'),
    meta: { title: '个人中心', requiresAuth: true }
  },
  {
    path: '/order-list',
    name: 'OrderList',
    component: () => import('../views/OrderList.vue'),
    meta: { title: '订单列表', requiresAuth: true }
  },
  {
    path: '/order-detail/:orderId',
    name: 'OrderDetail',
    component: () => import('../views/OrderDetail.vue'),
    meta: { title: '订单详情', requiresAuth: true }
  },
  {
    path: '/change-password',
    name: 'ChangePassword',
    component: () => import('../views/ChangePassword.vue'),
    meta: { title: '修改密码', requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHistory('/h5/'),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = to.meta.title
  }
  
  // 检查是否需要登录
  if (to.meta.requiresAuth) {
    const token = localStorage.getItem('token')
    if (token) {
      next()
    } else {
      console.log(to.fullPath)
      // 记录来源页面，登录成功后返回
      sessionStorage.setItem('redirectPath', to.fullPath)
      next({ name: 'Login' })
    }
  } else {
    next()
  }
})

export default router